// 生成基于时间戳和当天序号的检测单编号
async function generateDetectionNo(detectTime, vk, db, _, excludeId = null) {
	// 解析检测时间
	let date = new Date(detectTime);
	let year = date.getFullYear();
	let month = String(date.getMonth() + 1).padStart(2, '0');
	let day = String(date.getDate()).padStart(2, '0');
	let hour = String(date.getHours()).padStart(2, '0');
	let minute = String(date.getMinutes()).padStart(2, '0');

	// 生成时间戳前缀 yyyyMMddHHmm (12位)
	let timePrefix = `${year}${month}${day}${hour}${minute}`;

	// 获取当天的开始和结束时间戳
	let dayStart = new Date(year, date.getMonth(), day, 0, 0, 0).getTime();
	let dayEnd = new Date(year, date.getMonth(), day, 23, 59, 59, 999).getTime();

	// 构建查询条件，基于detect_time字段查询当天的记录
	let whereJson = {
		detect_time: _.gte(dayStart).and(_.lte(dayEnd))
	};

	// 如果是更新操作，排除当前记录
	if (excludeId) {
		whereJson._id = _.neq(excludeId);
	}

	// 查询当天已有的检测单数量，基于detect_time字段
	let count = await vk.baseDao.count({
		dbName: "tm-detection-form",
		whereJson: whereJson
	});

	// 生成序号，从1开始，补齐到5位 (总长度17位: 12位时间戳 + 5位序号)
	let sequence = count + 1;
	let sequenceStr = String(sequence).padStart(5, '0');

	return timePrefix + sequenceStr;
}

module.exports = {
	/**
	 * 添加单条数据
	 * @url admin/kong/sys/add 前端调用的url参数地址
	 * data 请求参数 说明
	 * res 返回参数说明
	 * @param {Number} code 错误码，0表示成功
	 * @param {String} msg 详细信息
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let { uid } = data;
		let res = { code: 0, msg: 'ok' };
		// 业务逻辑开始-----------------------------------------------------------
		let {

			client,
			client_name,
			type,
			detection_type,
			submitUser,
			detection_category,
			detection_standard_name,
			detection_standard,
			detection_user,
			sample_id,
			sampleno,
			samplename,
			sample_save_info,
			sample_keeptime,
			sample_troptime,
			sample_list,
			address,
			detect_time,
			submituser_address,
			addressps,
			contact,
			contact_number,
			remark,
sale_for
		} = data;
		// 这里需要把 params1 params2 params3 改成你数据库里允许用户添加的字段
		let dbName = "tm-detection-form",
			info = await vk.baseDao.findByWhereJson({
				dbName: "uni-id-users",
				whereJson: {
					nickname: detection_user,
				}
			}),
			_client_price = await vk.baseDao.findByWhereJson({
				dbName: "tm-client-price",
				whereJson: {
					client_id: client,
					category_id: detection_category
				}
			}),
			_price = 0,
			detection_user_sign = undefined;
		if (vk.pubfn.isNotNull(info) && vk.pubfn.isNotNull(info.sign_image)) {
			detection_user_sign = info.sign_image
		}


		// 生成基于时间戳和当天序号的编号
		let no = await generateDetectionNo(detect_time, vk, db, _);

		res.id = await vk.baseDao.add({
            dbName,
            dataJson: {
                no: no,
                detect_time,
                type,
                client,
                client_name,
                address,
                detection_type,
                submitUser,
                detection_category,
                detection_standard_name,
                detection_standard,
                detection_user,
                sample_id,
                sampleno,
                samplename,
                sample_save_info,
                sample_keeptime,
                sample_troptime,
				submituser_address,
				addressps,
                contact,
                contact_number,
                sale_for,
                remark,
                detection_user_sign: detection_user_sign
            }
        });

		if (sample_list != undefined && sample_list.length > 0) {
			if (vk.pubfn.isNotNull(_client_price) && vk.pubfn.isNotNull(_client_price.price))
				_price = vk.pubfn.string2Number(_client_price.price);
			let _add_sample_list = sample_list.map(x => {
				return {
					'detectionform_id': res.id,
					'client': client,
					'client_name': client_name,
					'detection_user': detection_user,
					'price': _price,
					...x
				}
			})
			let ids = await vk.baseDao.adds({
				dbName: "tm-sample-testing",// 表名
				dataJson: _add_sample_list
			});
		}
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
